package flexcommon.validators.support
{	
	/**
	 * <p>Class that peforms a Mod10 check against a string value.</p>
	 * 
	 * <p>Author: Dimitrios Gianninas</p>
	 */
	public class Mod10Check	{
		
		/**
		 * Default constructor.
		 */
		public function Mod10Check() 
		{
			
		}
		
		public function validate( str:String ):Boolean 
		{
			var weights:String = prepareWeights( str.length );
			
			if( str.length != weights.length ) {
      			return false;
		    }
		    else {
				var end:int = str.length-1;
				var sum:int = 0;
				var prod:int = 0;
				
				for ( var i:int = end; i >= 0; i--) {
					prod = ( int(str.charCodeAt( i )) - 48 ) * int(weights.charAt( i ));
					
					if( prod >= 10 ) {
						sum += ( prod / 10 + prod % 10);
					}
					else {
						sum += prod;
					}
				}
				
				return ( sum % 10 == 0 );
		    }
		}
		
		private function prepareWeights( strLength:int ):String 
		{
			var weights:String = "";		
			
			var sign:int = 1;
			var val:int = 1;
			
			for( var i:int = strLength - 1; i >= 0; i-- ) {
				weights = val + weights;
			
				val += sign;
				sign *= -1;
			}
			
			return weights;
		}		
	}
}